<?php

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\validate\AddressNew;
use think\Controller;
use think\Request;
use app\api\service\Token as TokenService;
use app\api\model\User as UserModel;
use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\SuccessMessage;
use app\lib\exception\TokenException;
use app\lib\exception\UserException;

class Address extends BaseController
{
    // 前置操作。需继承think\Controller
    // 键名为前置方法、键值中的方法名必须小写
    protected $beforeActionList = [
        'checkPrimaryScope' => ['only' => 'createorupdateaddress'],
    ];

    
    
    public function createOrUpdateAddress()
    {
        $validate = new AddressNew();
        $validate->goCheck();
        /**
         * 根据Token获取用户Uid
         * 根据Uid判断用户是否存在，若不存在则抛出异常。
         * 获取用户从客户端提交的地址信息
         * 根据用户地址信息是否存在，从而判断添加地址或更新地址
         */
        $uid = TokenService::getCurrentUid();
        $user = UserModel::get($uid);
        if (!$user) {
            throw new UserException();
        }

        $dataArray = $validate->getDataByRule(input('post.'));

        $userAddress = $user->address;
        if (!$userAddress) {
            // 不存在则添加
            $user->address()->save($dataArray);
        } else {
            // 存在则更新
            $user->address->save($dataArray);
        }
        return json(new SuccessMessage(), 201);
    }
}
